package com.cordys.uc.webapps.translator;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HTMLTranslator {

    private File srcFile;
    int offset = 0;
    static String strhead = "";

    public static String getStrhead() {
        return strhead;
    }

    public static void setStrhead(String strhead) {
        HTMLTranslator.strhead = strhead;
    }
    FileReader input = null;
    BufferedReader bufRead = null;
    static LineNumberReader lnreader = null;

    static public LineNumberReader getLnreader() {
        return lnreader;
    }

    static public void setLnreader(LineNumberReader lnreader) {
        HTMLTranslator.lnreader = lnreader;
    }
    static HashMap<Object, Object> xlmap = null;
    String BASE_PATH = "";
    String XLFILE = "\\multilanguage\\messages\\labels\\CPFMessages.xls";
    String LOGREPLACEFILE = "\\multilanguage\\messages\\logs\\Replace.log";
    String LOGEXCEPTIONFILE = "\\multilanguage\\messages\\logs\\Exception.log";
    int MODIFYSRC = 0;
    int LOGALL = 0;
    String LOGDELIM = "`";
    BufferedWriter wrlog_exception = TranslationLogger.wrlog_exception;

    HTMLTranslator(File srcFile) {
        this.srcFile = srcFile;
    }

    void translate() {
        process(wrlog_exception, srcFile.getAbsolutePath());
    }

    public void process(BufferedWriter wrlog_exception, String file) {
        offset = 0;
        strhead = "";
        input = null;
        bufRead = null;
        lnreader = null;
        try {
            String tmpcmp = "";
            //get the contents of the file
            String html = FileUtil.getFile(file);
            System.out.println("Processing file....  " + file);

            ArrayList<String> xldata = new ArrayList();
            String tmp = "";
            //System.out.println(html);
            lnreader.mark(0);
            lnreader.reset();
            offset = 0;
            tmp = html;

            //check for pattern similar to >test</
            Pattern p = Pattern.compile("[^\\/]>[^<>]+<\\/");
            //get the matches for the above pattern from html
            Matcher m = p.matcher(html);
            int c = 1;
            //loop thru all found matches
            while (m.find()) {
                //remove all space new line carriage return and trim
                String t = m.group().replaceAll("\\n|\\r|\\s", "").trim();

                if (!(t.contains("></"))) {
                    //add the found match to hashmap
                    xldata.add(m.group());
                    c++;
                    //get the line number of the matched pattern from the html file
                    int lno = FileUtil.getLineNo(m.start(), tmp, html);
                    tmpcmp = tmp;
                    String tt = tmp.substring(0, m.start());
                    if (tt.lastIndexOf(">") < tt.lastIndexOf("/")) {
                        //adds span tag for the text element
                        tmp = addSpanTag(tmp.substring(0, m.start() + 2 + offset), tmp.substring(m.start() + 2 + offset));

                    } else {
                        //adds translatable='true' attribute
                        tmp = addTranslatableAttr(tmp.substring(0, m.start() + 2 + offset), tmp.substring(m.start() + 2 + offset));
                    }

                    if (!tmpcmp.equals(tmp)) {
                        //log the replaced change
                        TranslationLogger.log("HTML", file, lno + FileUtil.getNewLines(strhead), FileUtil.getLine(lno, html));

                    }


                }

            }


            lnreader.mark(0);
            lnreader.reset();
            offset = 0;
            html = tmp;

            //check for pattern similar to /><
            p = Pattern.compile("\\/>[^<>]+<[^\\/]");
            //get the matches for the above pattern from html
            m = p.matcher(html);
            //loop thru all found matches
            while (m.find()) {
                //remove all space new line carriage return and trim
                String t = m.group().replaceAll("\\n|\\r|\\s", "").trim();
                if (!(t.contains("/><"))) {
                    //add the found match to hashmap
                    xldata.add(m.group());
                    //get the line number of the matched pattern from the html file
                    int lno = FileUtil.getLineNo(m.start(), tmp, html);
                    tmpcmp = tmp;
                    //adds span tag for the text element
                    tmp = addSpanTag(tmp.substring(0, m.start() + 2 + offset), tmp.substring(m.start() + 2 + offset));
                    if (!tmpcmp.equals(tmp)) {
                        //log the replaced change
                        TranslationLogger.log("HTML", file, lno + FileUtil.getNewLines(strhead), FileUtil.getLine(lno, html));

                    }
                }

            }

            lnreader.mark(0);
            lnreader.reset();
            offset = 0;
            html = tmp;
            //                ><
            p = Pattern.compile("[^\\/]>[^<>]+<[^\\/]"); //Pattern.compile(">[^<>]+<\\/");
            m = p.matcher(html);
            while (m.find()) {
                String t = m.group().replaceAll("\\n|\\r|\\s", "").trim();
                if (!(t.contains("><"))) {
                    //System.out.println("%" + m.group() + " =" + m.start());// .group(0));
                    xldata.add(m.group());
                    int lno = FileUtil.getLineNo(m.start(), tmp, html);
                    tmpcmp = tmp;
                    tmp = addSpanTag(tmp.substring(0, m.start() + 2 + offset), tmp.substring(m.start() + 2 + offset));
                    if (!tmpcmp.equals(tmp)) {
                        TranslationLogger.log("HTML", file, lno + FileUtil.getNewLines(strhead), FileUtil.getLine(lno, html));

                    }
                }

            }

            lnreader.mark(0);
            lnreader.reset();
            offset = 0;
            html = tmp;
            //                   /></
            p = Pattern.compile("\\/>[^<>]+<\\/"); //Pattern.compile(">[^<>]+<\\/");
            m = p.matcher(html);
            while (m.find()) {
                String t = m.group().replaceAll("\\n|\\r|\\s", "").trim();
                if (!(t.contains("/></"))) {
                    //System.out.println("$" + m.group() + " =" + m.start());// .group(0));
                    xldata.add(m.group());
                    int lno = FileUtil.getLineNo(m.start(), tmp, html);
                    tmpcmp = tmp;
                    tmp = addSpanTag(tmp.substring(0, m.start() + 2 + offset), tmp.substring(m.start() + 2 + offset));
                    if (!tmpcmp.equals(tmp)) {
                        TranslationLogger.log("HTML", file, lno + FileUtil.getNewLines(strhead), FileUtil.getLine(lno, html));

                    }
                }

            }



            lnreader.mark(0);
            lnreader.reset();
            offset = 0;
            html = tmp;
            //
            p = Pattern.compile("title\\="); //Pattern.compile(">[^<>]+<\\/");
            m = p.matcher(html);
            while (m.find()) {
                String t = m.group();
                int lno = FileUtil.getLineNo(m.start(), tmp, html);
                tmpcmp = tmp;
                String strtit = tmp.substring(m.start());
                tmp = addTranslatableAttr(tmp.substring(0, m.start() + strtit.indexOf(">") + 1), tmp.substring(m.start() + strtit.indexOf(">") + 1));
                if (!tmpcmp.equals(tmp)) {
                    TranslationLogger.log("HTML", file, lno + FileUtil.getNewLines(strhead), FileUtil.getLine(lno, html));

                }


            }



            InlineJavascriptTranslator.processinlinejs(strhead, file);

            TranslationLogger.writetoXL(file, xldata);


        } catch (Exception ex) {
        }
    }

    private String addSpanTag(String part1, String part2) {
        if (part1.trim().lastIndexOf(">") == (part1.trim().length() - 1)) {
            String t = part2.substring(0, part2.indexOf("<"));
            part2 = part2.substring(part2.indexOf("<"));
            if (!t.contains("&nbsp;")) {
                part1 += "<span translatable=\"true\">" + t + "</span>";
                offset += "<span translatable=\"true\"></span>".length();

            } else {
                if (t.trim().startsWith("&nbsp;")) {
                    String nbsp = "";
                    while (t.trim().startsWith("&nbsp;")) {
                        nbsp += t.substring(0, t.indexOf("&nbsp;") + 6);
                        t = t.substring(t.indexOf("&nbsp;") + 6);
                    }
                    part1 += nbsp;
                    if (!t.isEmpty()) {
                        part1 += "<span translatable=\"true\">" + t + "</span>";
                        offset += "<span translatable=\"true\"></span>".length();
                    }
                } else {
                    String nbsp = "";
                    while (t.trim().endsWith("&nbsp;")) {
                        nbsp += t.substring(t.lastIndexOf("&nbsp;"));
                        t = t.substring(0, t.lastIndexOf("&nbsp;"));
                    }

                    part1 += "<span translatable=\"true\">" + t + "</span>" + nbsp;
                    offset += "<span translatable=\"true\"></span>".length();
                }
            }

            part1 = part1 + part2;
        }
        return part1;
    }

    private String addTranslatableAttr(String part1, String part2) {


        if (part1.trim().lastIndexOf(">") == (part1.trim().length() - 1)) {
            part1 = part1.substring(0, part1.length() - 1);
            if (!part1.substring(part1.lastIndexOf("<")).contains("translatable=")) {
                part1 += " translatable=\"true\">";
                offset += " translatable=\"true\">".length() - 1;
                //System.out.println("DEBUG:ATTR:"+offset);

            } else {
                part1 += ">";
            }
            part1 = part1 + part2;
        }
        return part1;
    }
}
